package charlie.shop.admin;

import com.charlie.beans.Groups;
import com.charlie.beans.GroupsRoles;
import com.charlie.beans.Roles;
import com.charlie.sessions.GroupsFacadeLocal;
import com.charlie.sessions.GroupsRolesFacadeLocal;
import com.charlie.sessions.RolesFacadeLocal;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Create new group servlet
 *
 * @author Gleb
 */
@WebServlet(name = "CreateGroup", urlPatterns = {"/admin/createGroup"})
public class CreateGroup extends HttpServlet {

    @EJB
    private GroupsRolesFacadeLocal groupsRolesFacade;
    @EJB
    private GroupsFacadeLocal groupsFacade;
    @EJB
    private RolesFacadeLocal rolesFacade;

    /**
     * Get roles information and show create group page
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute("roles", rolesFacade.findAll());
        getServletContext().getRequestDispatcher("/admin/createGroup.jsp").forward(request, response);
    }

    /**
     *
     * Create new group
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Groups group = new Groups();
        group.setName(request.getParameter("groupName"));
        groupsFacade.create(group);

        //if some roles are checked
        String select[] = request.getParameterValues("id");
        if (select != null) {
            for (String roleName : select) {
                GroupsRoles gr = new GroupsRoles();
                Roles r = rolesFacade.findByRolesName(roleName);
                gr.setRolesId(r);
                gr.setGroupsId(group);
                groupsRolesFacade.create(gr);
            }
        }
        getServletContext().getRequestDispatcher("/admin/completeCreation.jsp").forward(request, response);
    }
}
